<template>
  <div class="myaddress">
    <mydjitopnav />
    <div class="container">
      <h1>安全结账</h1>
      <div class="main">
        <div class="main_left">
          <div class="receiving_address">
            <div class="address_top">
              <h3>收货地址</h3>
              <!-- <a >新增收货地址</a> -->
              <a type="primary" @click="showAddModal"> 新增收货地址 </a>
            </div>
            <!-- <address-record v-if="addressList.length>0"></address-record> -->
            <div class="addressRecord" v-if="addressList.length > 0">
              <div class="record" v-if="defaultAddress.length>0" :class="{active1:defaultAddress[0].id===recordId}" @click="recordClick(defaultAddress[0].id)">
                <div class="record_left">
                  <div>
                    <span class="identity">{{defaultAddress[0].name}}({{defaultAddress[0].phone}})</span>
                    <span class="default">默认</span>
                  </div>
                  <span class="address">{{defaultAddress[0].area_name + defaultAddress[0].desc}}</span>
                </div>
                <div class="record_right">
                  <a class="modify" @click="showEditModal(defaultAddress[0])">修改</a>
                  <a class="del" @click="showDelModal(defaultAddress[0])">删除</a>
                </div>
              </div>
              <div class="record" v-for="item in noDefaultAddress" :key="item.id" :class="{active1:item.id===recordId}" @click="recordClick(item.id)">
                <div class="record_left">
                  <div>
                    <span class="identity">{{item.name}}({{item.phone}})</span>
                    <!-- <span class="default">默认</span> -->
                  </div>
                  <span class="address">{{item.area_name + item.desc}}</span>
                </div>
                <div class="record_right">
                  <a class="modify" @click="showEditModal(item)">修改</a>
                  <a class="del" @click="showDelModal(item)">删除</a>
                </div>
              </div>
            </div>
            <div class="noAddress" v-if="noDefaultAddress.length === 0">
              <span class="span1">快来新增收货地址把！ <span>+</span></span>
            </div>
            <div class="address_modal">
              <a-modal v-model="visible" class="popup" :title="modalTitle">
                <div class="form">
                  <div>
                    <a-input value="中国" disabled />
                  </div>
                  <div>
                    <a-input
                      v-model="checkedItem.name"
                      @blur="checkName"
                      placeholder="姓名"
                    />
                    <span class="tip">{{nameTip}}</span>
                  </div>
                  <div>
                    <a-input
                      v-model="checkedItem.phone"
                      @blur="checkPhone"
                      placeholder="手机号"
                    />
                    <span class="tip">{{phoneTip}}</span>
                  </div>
                  <div class="cascader">
                    <a-cascader
                      :options="options"
                      v-model="checkedItem.area"
                      placeholder="地址"
                      :default-value="defaultValue"
                      @blur="checkAddress"
                      @change="onChange"
                      @popupVisibleChange="onPopupVisibleChange"
                    >
                    </a-cascader>
                    <span class="addressTip">{{areaTip}}</span>
                  </div>
                  <div>
                    <a-input
                      v-model="checkedItem.desc"
                      @blur="checkDetail"
                      placeholder="详细地址"
                    />
                    <span class="tip">{{descTip}}</span>
                  </div>
                  <a-checkbox @change="setDefault">设为默认</a-checkbox>
                </div>
                <template slot="footer">
                  <a-button key="back" @click="handleCancel"> 取消 </a-button>
                  <a-button key="submit" type="primary" @click="handleOk()">
                    保存
                  </a-button>
                </template>
              </a-modal>
              <a-modal v-model="delVisible" class="delAdr" title="删除地址" style="textAlign:center;">
                <span>你确定要删除吗</span>
                <template slot="footer">
                  <a-button key="back" @click="delhandleCancel"> 取消 </a-button>
                  <a-button key="submit" type="primary" @click="delhandleOk()">
                    保存
                  </a-button>
                </template>
              </a-modal>
            </div>
          </div>
          <div class="distribution">
            <h3>配送方式</h3>
            <div class="mode">
              <span>标准物流 - 免费</span>
              <span>发货后，需2-4天派送时间</span>
            </div>
          </div>
        </div>
        <div class="main_right">
          <div class="order_overview">
            <div class="overview_top">
              <h3>订单概览</h3>
              <router-link :to="{ path: '/cart' }">编辑购物车</router-link>
            </div>
            <div class="order">
              <div class="order-record" v-for="item in order" :key="item.id">
                <div class="record_left">
                  <div class="img">
                    <img :src="item.s_good.s_goods_photos[0].path" alt="" />
                  </div>
                  <div class="info">
                    <span class="productName">{{ item.s_good.name }}</span>
                    <span>¥{{ item.s_good.price }} x {{ item.num }}</span>
                  </div>
                </div>
                <div class="record_right">
                  <span>￥{{ item.s_good.price * item.num }}</span>
                </div>
              </div>
            </div>
            <div class="price">
              <div class="total">
                <span>商品总金额:</span>
                <span>￥{{ allPrice }}</span>
              </div>
              <div class="freight">
                <span>运费:</span>
                <span>￥0</span>
              </div>
              <div class="cope_with">
                <span>应付金额:</span>
                <span>￥{{ allPrice + this.freight }}</span>
              </div>
            </div>
            <div class="submission">
              <p>提交订单即表示我同意 DJI 大疆商城的<span>销售政策</span></p>
              <button @click="placeOrder">提交订单</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <bottomnav />
  </div>
</template>

<script>
import mydjitopnav from "../components/MyDjiTopNav.vue";
import bottomnav from "../components/BottomNav.vue";

import { getCity,addAddress,setAddress,delAddress,setDefaultAddress,addOrder } from "../assets/js/request.js";

import { mapState, mapActions,mapGetters } from "vuex";

let nameReg = /^[\u4E00-\u9FA5A-Za-z0-9]{2,20}$/;
let phoneReg = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
export default {
  data() {
    return {
      order: JSON.parse(localStorage.getItem("order")),
      freight: 0,
      // 地址数据
      visible: false,
      delVisible: false,
      options: [],
      checkedItem: {},
      nameTip:'',
      phoneTip:'',
      areaTip:'',
      descTip:'',
      // 城市地址信息
      cityName:'',
      // 地址id
      cityId:'',
      // 提示框标题
      modalTitle:'',
      // 判断是哪个请求的标志
      handleOkIndex:'',
      // 点击修改时弹出框三级联动的默认地址
      defaultValue:[],
      // 用于在修改时判断是否已触发change事件
      isChange:0,
      // 点击地址时改变其值，用于判断所点击的地址并为其改变样式
      recordId:'',
      // 用于设置默认地址
      checked:false,

      // tips:{}
    };
  },
  components: {
    bottomnav,
    mydjitopnav,
  },
  computed: {
    ...mapState("address", ["addressList","defaultAddress"]),
    ...mapGetters("address",['noDefaultAddress','defaultAddress']),
    allPrice() {
      return this.order.reduce(
        (num, prod) => num + prod.num * prod.s_good.price,
        0
      );
    },
  },
  methods: {
    ...mapActions("address", ["getAddress"]),
    // ...mapActions('order',['addOrder']),
    // 点击地址，改变样式
    recordClick(id) {
      this.recordId = id;
      console.log(this.recordId);
    },
    showAddModal() {
      this.modalTitle = '添加地址';
      this.handleOkIndex = "0";
      this.visible = true;
    },
    showEditModal(item) {
      this.modalTitle = '修改地址';
      this.handleOkIndex = "1";
      this.cityId = item.id;
      // 点击修改时弹出框显示之前的内容
      this.checkedItem = {
        name:item.name,
        phone:item.phone,
        area_name:item.area_name,
        desc:item.desc,
      };
      console.log(item.area);
      let area = item.area.split(',');
      console.log(area);
      this.defaultValue = [+area[0],+area[1],+area[2]];
      console.log(item.area);
      this.visible = true;
    },
    showDelModal(item) {
      this.handleOkIndex = "2"
      this.cityId = item.id
      this.delVisible = true;
    },
    handleCancel() {
      this.checkedItem = {};
      this.visible = false;
    },
    delhandleCancel() {
      this.delVisible = false;
    },
    // 提交数据验证（注意：如果数据是通过v-model绑定到一个对象里，所判断的
    // 每一个数据为空时将不能用""来判断，而应该用undefined来判断
    checkName() {
      if (this.checkedItem.name === undefined) {
        this.nameTip = "姓名必填";
      } else if (!nameReg.test(this.checkedItem.name)) {
        this.nameTip = "姓名格式不对";
      } else {
        this.nameTip = "";
      }
    },
    checkPhone() {
      console.log(this.checkedItem);
      console.log(this.checkedItem.phone);
      if (this.checkedItem.phone === undefined) {
        this.phoneTip = "手机号必填";
      } else if (!phoneReg.test(this.checkedItem.phone)) {
        this.phoneTip = "手机号格式不对";
      } else {
        this.phoneTip = "";
      }
    },
    checkAddress() {
      if (this.checkedItem.area === undefined) {
        this.areaTip = "地址必填";
      } else {
        this.areaTip = "";
      }
    },
    checkDetail() {
      if (this.checkedItem.desc === undefined) {
        this.descTip = "详细地址必填";
      } else {
        this.desclTip = "";
      }
    },

    // 通过onChange事件获取地址
    onChange(value,selectedOptions) {
      // console.log(selectedOptions);
      this.cityName = selectedOptions.map(ele=>ele.cityname);
      if(this.handleOkIndex === '1') {
        this.isChange = 1;
      }
      
    },
    onPopupVisibleChange(value) {
      console.log(value);
    },
    // 点击确认时的逻辑判断
    async handleOk() {
      if(this.handleOkIndex === '0') {// 为0时，触发添加事件
        let data1 = {
          name:this.checkedItem.name,
          phone:this.checkedItem.phone,
          area:`${this.checkedItem.area}`,
          area_name:`${this.cityName}`,
          desc:this.checkedItem.desc,
        };
        let address = await addAddress(data1);
        console.log(address);
        this.getAddress()
      }else if(this.handleOkIndex === '1') {// 为1时，触发修改事件
        // 修改地址时，通过之前设置的isChange来判断地址选择器（change事件）是否已触发
        // let cityName;
        // if(this.isChange === 1) {
        //   cityName = `${this.cityName}`.split(',').join("");
        // }else {
        //   cityName = this.checkedItem.area_name;
        // }
        let data2 = {
          name:this.checkedItem.name,
          phone:this.checkedItem.phone,
          area:`${this.checkedItem.area}`,
          area_name:`${this.cityName}`.split(',').join(""),
          desc:this.checkedItem.desc,
        };
        let edit = await setAddress(this.cityId,data2);
        console.log(edit);
        if(edit && this.checked) {
          let defaultAde = await setDefaultAddress(edit.id);
          console.log(defaultAde);
        }
        // 点击确定时，将之前修改提示框里的显示信息清除，避免影响添加提示框，取消按钮同理
        this.checkedItem = {};
        // this.isChange = 0;
        // this.defaultValue = [];
        this.getAddress();
      }
      this.visible = false;
    },
    async delhandleOk() {
      console.log(this.cityId);
      let del = await delAddress(this.cityId);
      // console.log(del);
      this.getAddress();
      this.delVisible = false;
    },
    // 默认地址checkbox
    setDefault(e) {
      if(e.target.checked) {
        this.checked = true
      }else {
        this.checked = false
      }
    },

    // 点击提交添加订单
    async placeOrder() {
      // console.log(this.recordId);
      let addr_id;
      if(this.recordId==='') {
        console.log(this.defaultAddress[0].id);
        addr_id = this.defaultAddress[0].id;
      }else {
        console.log(this.recordId);
        addr_id = this.recordId
      }
      console.log(addr_id);
      let goods_info = [];
      this.order.forEach((ele,index)=> {
        goods_info.push({id:ele.goods_id,num:ele.num});
        console.log(goods_info[index] );
      })
      console.log(goods_info);
      let data = {
        goods_info:goods_info,
        addr_id:addr_id,
        project_id:26,
      };
      console.log(data);
      let order = await addOrder(data)
      console.log(order);
      this.$router.push(`/order/${order.id}`);
    }
  },


  async created() {
    // 三级联动获取城市数据
    let city = await getCity();
    console.log(city);
    this.options = city;
    // 初始化阶段获取地址数据
    this.getAddress();
    console.log(this.noDefaultAddress);
    console.log(this.defaultAddress);
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/scss/myAddress";
</style>